//
//  NetworkTools+OAut.swift
//  weibo
//
//  Created by 陈勇 on 16/2/26.
//  Copyright © 2016年 chenyong. All rights reserved.
//

import Foundation

extension NetworkTools{
    

    var oauthURL: NSURL{
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appkey)&redirect_uri=\(redirectUri)"
        
        return NSURL(string: urlString)!
        
    }
    
    
    
    /// 加载 access token
    ///
    /// - parameter code:     code 授权码
    /// - parameter finished: 完成回调 (字典)
    func loadAccessToken(code: String, finished: ([String: AnyObject]?)->()){
    
        let urlString = "https://api.weibo.com/oauth2/access_token"
            
        let params = ["client_id": appkey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]
        
        
        // result 是 token 的结果字典，是可选的！
        // 如果要使用 key 从字典中取值，必须保证字典存在
        request(.POST,URLString: urlString, parameters: params) {[weak self] result in
            
            guard let result = result,
                let access_token = result["access_token"] as? String,
                let uid = result["uid"] as? String else {
            
                    print("数据格式不正确")
                
                // 一定要完成回调，通知调用方请求失败
                finished(nil)
                return
            }
            //继续加载用户数据
            self?.loadUser(access_token, uid: uid, finished: { (userDict) -> () in
                //合并字典
                //判断用户是否有值
                guard var userDict = userDict else{
                
                    print("用户数据加载失败")
                    finished(nil)
                    return
                }
                //合并字典
                for (k, v) in result{
                    userDict[k] = v
                }
                
                //完成回调
                finished(userDict)
            })
        }
    }
}

